#!/bin/bash

usage() {
	echo "
 generate desktop files and file associations
 for rox, pcmanfm (and other files managers)
   needs ${SYSROOT}/etc/pmime.conf

 Usage: $0 [-sysroot PATH|-norox] <command>

 -sysroot: use alternate root (or export $SYSROOT)
 -norox: do not process ROX stuff..

 Commands:
  -fddb          download and store latest freedesktop.org.xml
  -mimedefs      create mime associations for different standards
                 using ${SYSROOT}/etc/pmime.conf
                 be careful, this will (over)write a lot of files
  -desktop       create files in ${SYSROOT}${HOME}/Desktop
  -system        -mimedefs + -desktop
"
	exit
}


if [ -f $SYSROOT/etc/pmime.conf ] ; then
	. $SYSROOT/etc/pmime.conf
else
	. /etc/pmime.conf
fi

#===================================
#			mimedbs
#===================================
freedesktop_mimedb_download() {
	cd /tmp
	wget -c http://cgit.freedesktop.org/xdg/shared-mime-info/plain/freedesktop.org.xml.in
	if [ $? -ne 0 ] ; then
		echo "ERROR downloading freedesktop.org.xml" >&2
		rm -f freedesktop.org.xml.in
		return 1
	else
		mkdir -p ${SYSROOT}/usr/share/mime/packages
		mv -f freedesktop.org.xml.in ${SYSROOT}/usr/share/mime/packages/freedesktop.org.xml
	fi
	#fixes to freedesktop.org.xml
	sed -i -e '/\*.tgz/d' -e '/\*.txz/d' ${SYSROOT}/usr/share/mime/packages/freedesktop.org.xml #slackware: puppy.xml
	echo "${SYSROOT}/usr/share/mime/packages/freedesktop.org.xml downloaded"
}

#===================================
#			-mimedefs
#===================================

process_exec() {
	local app="" exec=""
	mkdir -p /tmp/mimedefs/exec
	while IFS="=" read app exec ; do
		[ "$exec" ] && echo "$exec" > "/tmp/mimedefs/exec/${app}"
	done <<< "$APP_EXEC"
}

## /tmp/mimedefs/exec/$app
check_exec() {
	if [ -f "/tmp/mimedefs/exec/$1" ] ; then
		echo "$(< "/tmp/mimedefs/exec/$1")"
	else
		echo "$1"
	fi
}

## app;app2;app3;etc
format_app() {
	local appz="$@"
	local res=$(
		IFS=";" app=""
		for app in ${appz} ; do
			[ ! "$app" ] && continue
			echo -n "${app}.desktop;"
		done
	)
	echo "${res%\;}"
}

## app;app2;app3;etc
desktop_file() {
	local appz="$@" IFS=";" app=""
	for app in ${appz}
	do
		[ ! "$app" ] && continue
		[ -f "applications/${app}" ] && continue #/tmp/mimedefs, process_desktop()
		echo -e "[Desktop Entry]
Encoding=UTF-8
Type=Application
NoDisplay=true
Name=${app}
Exec=$(check_exec "${app}")" > applications/${app}.desktop #%F
	done
}

#--

rox_default() {
	local mimetype="$1" ; shift
	local roxmimetype="${mimetype//\//_}"
	local app="$@"
	app=${app%%;*}
	app="$(check_exec "${app}")"
	echo -e "#!/bin/sh\nexec $app \"\$@\"" > MIME-types/${roxmimetype}
	chmod +x MIME-types/${roxmimetype}
}

## app;app2;app3;etc
rox_associations() {
	local mimetype="$1" ; shift
	local roxmimetype="${mimetype//\//_}"
	local appz="$@" IFS=";" app=""
	for app in ${appz}
	do
		[ ! "$app" ] && continue
		mkdir -p "OpenWith/.${roxmimetype}"
		app="$(check_exec "${app}")"
		echo -e "#!/bin/sh\nexec $app "'"$@"' > "OpenWith/.${roxmimetype}/$app"
		chmod +x "OpenWith/.${roxmimetype}/$app"
	done
}

#--

mimedefs() {
	
	process_exec

	# -- mime_defaults
	mkdir -p /tmp/mimedefs ; cd /tmp/mimedefs
	[ -z "$NOROX" ] && mkdir -p MIME-types applications
	mkdir -p applications
	echo "[Default Applications]" > defaults.list
	echo -n > mailcap
	while IFS="=" read mimetype app
	do
		[ ! "$app" ] && continue
		echo "${mimetype}; $(check_exec ${app%%;*}) \"%s\"" >> mailcap
		echo "${mimetype}=$(format_app ${app})" >> defaults.list
		desktop_file ${app}
		[ -z "$NOROX" ] && rox_default ${mimetype} ${app}
	done <<< "$(echo "$MIME_DEFAULTS" | grep -v -E '^#|\[')"

	# -- mime_associations
	mkdir -p /tmp/mimedefs ; cd /tmp/mimedefs
	[ -z "$NOROX" ] && mkdir -p OpenWith
	mkdir -p applications
	echo "[Added Associations]" > alt.list
	while IFS="=" read mimetype app
	do
		[ ! "$app" ] && continue
		echo "${mimetype}=$(format_app ${app})" >> alt.list
		desktop_file ${app}
		[ -z "$NOROX" ] && rox_associations ${mimetype} ${app}
	done <<< "$(echo "$MIME_ASSOCIATIONS" | grep -v -E '^#|\[')"

	( cat defaults.list ; echo ; cat alt.list ) > mimeapps.list
	rm -f defaults.list alt.list
}

#--

mimedefs_apply() {
	cd /tmp/mimedefs || return 1

	(
	if [ "$SYSROOT" != "" ] ; then
		if [ -z "$NOROX" ] ; then
			mkdir -p "${SYSROOT}${HOME}/Choices"
			mkdir -p "${SYSROOT}${HOME}/.config/rox.sourceforge.net"
		fi
		mkdir -p ${SYSROOT}/etc
		mkdir -p ${SYSROOT}/usr/share/applications
	fi

	local file="" filez="$(ls ${PWD}/applications/* 2>/dev/null)"
	echo "$filez" | while read file
	do
		name="${file##*/}"
		name="${name%.desktop}"
		[ -f "${SYSROOT}/usr/share/applications/${name}.desktop" ] && echo "not copying: $file" && continue
		cp -fv "$file" "${SYSROOT}/usr/share/applications/${name}.desktop"
	done

	if [ -z "$NOROX" ] ; then
		cp -rv --remove-destination MIME-types "${SYSROOT}${HOME}/Choices"
		cp -rv --remove-destination OpenWith "${SYSROOT}${HOME}/.config/rox.sourceforge.net"
	fi
	cp -fv mailcap ${SYSROOT}/etc/mailcap #$HOME/.mailcap
	cp -fv mimeapps.list ${SYSROOT}/usr/share/applications/mimeapps.list #$HOME/.local/share/applications/mimeapps.list
	rm -fv ${SYSROOT}/usr/share/applications/defaults.list
	rm -fv ${SYSROOT}/usr/share/applications/mimeinfo.cache #this file is always trouble
	) > /tmp/pmime.log
}

#===========================================
#               DESKTOP
#===========================================

desktop() {
	DDIR=${SYSROOT}$HOME/Desktop
	mkdir -p ${DDIR}
	#default_apps='archiver audioeditor audiomixer audioplayer barehtmlviewer browser calendar cdplayer cdrecorder chat chmviewer connect contact draw email filemanager htmleditor htmlviewer imageeditor imageviewer mediaplayer musicplayer paint pdfviewer processmanager screenshot run search spreadsheet terminal texteditor textviewer wordprocessor'
	apps='filemanager archiver connect browser run terminal texteditor wordprocessor cdrecorder'
	for i in $apps
	do
		cp ${SYSROOT}/usr/share/applications/default${i}.desktop ${DDIR}/
	done
	sed -i 's|Default ||' ${DDIR}/*.desktop
	for i in Wizard-Wizard.desktop puppyapps.desktop \
		Puppy-Event-Manager.desktop BootManager-configure-bootup.desktop
	do
		cp ${SYSROOT}/usr/share/applications/${i} ${DDIR}/
	done
}

#===========================================
#                 MAIN
#===========================================

[ -z "$1" ] && usage

for arg in $@
do
	case $1 in
		-prefix|-sysroot)
			if [ "$2" -a -d "$2" ] ; then
				SYSROOT=$(realpath $2)
				if [ -f $SYSROOT/etc/pmime.conf ] ; then
					. $SYSROOT/etc/pmime.conf
				fi
			fi
			shift
			;;
		-norox)
			NOROX=1
			;;
		-fddb)   freedesktop_mimedb_download ; exit ;;
		-mimedefs|mimedefs)
			mimedefs
			[ "$TEST" ] && exit
			mimedefs_apply ; rm -rf /tmp/mimedefs
			exit
			;;
		-mimedefsa) mimedefs_apply ; exit ;;
		-desktop|desktop) desktop ; exit ;;
		-system|system)
			#freedesktop_mimedb_download
			mimedefs
			mimedefs_apply
			desktop
			rm -rf /tmp/mimedefs
			exit
			;;
		*)
			usage
			exit
			;;
	esac
	shift
done

### END ###